import React from 'react'
import { Input, Form, SubmitInput, Success } from './DOMElements.js'
import {history} from '../App';
import { useMutation} from '@apollo/client';
import { CREATE_USER } from '../mutations/user.js';
// import { GET_ALL_USERS } from '../query/user.js';

export default function FirstModal() {
  const [email, setEmail] = React.useState('')
  const [flag, setFlag] = React.useState(false)
  const [newUser] = useMutation(CREATE_USER)
  // const {data, loading} = useQuery(GET_ALL_USERS) 
  // const [users, setUsers] = React.useState()
  // console.log(data)
  // React.useEffect(() => {
  //   if (!loading) {
  //     setUsers(data.getAllUsers)
  //     console.log(users)
  //   }
  // }, [data])

  const validateEmail = value => {
    let pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    if (!pattern.test(value)) return false
    return true
  }

  const handleChange = (event) => {
    event.preventDefault()
    validateEmail(event.target.value)
    
    if (validateEmail(event.target.value)) {
      setEmail(event.target.value)
    }
  }

  const handleSubmit = (event) => {
    // event.preventDefault()
    if (email !== '') {
      setFlag(true)

      newUser({
        variables: {
          input: {
            email: email
          }
        }
      }).then(({data}) => {
        //console.log(data)
        setEmail('')
      })
      history.push("/validate")
    }
  }

  return (
    <div>
      {flag &&
        <Success>Почта успешно отправлена!</Success>
      }
      <Form onSubmit={event => handleSubmit(event)}>
        <Input type="email" placeholder="Email" onChange={event => handleChange(event)}/>
        <SubmitInput type="submit" placeholder="Отправить"/>
      </Form>
    </div>
  )
}
